<template>
  <view v-if="detailInfo" class="relative full-screen uni-bg-white">
    <uni-nav-bar ref="navBar" class="absolute" style="z-index:10;" statusBar :border="false" backgroundColor="transparent" @clickLeft="goBack">
      <template v-slot:left>
        <image class="size-32" src="@/static/svg/icon-back.svg" />
      </template>
    </uni-nav-bar>
    <scroll-view class="relative flex-col" :scroll-top="scrollTop" :style="`height:calc(100% - ${detailInfo.remainStock === 0 && !isLink ? 0 : 52}px - ${safeAreaBottom}px);`" scroll-y>
      <uni-swiper-dot mode="round" :info="photos && photos.length <= 1 ? [] : photos" :current="swiperDotIndex" :dotsStyles="{ bottom: 8, selectedBackgroundColor: 'white', selectedBorder: 'white' }">
        <swiper class="swiper-box" autoplay circular :interval="2000" @change="swiperChange" :current="swiperDotIndex">
          <swiper-item v-for="(item, index) in photos" :key="index">
            <view class="swiper-item">
              <video v-if="isVideoFile(item)" class="h-full" :src="item"></video>
              <image v-else class="h-full" mode="aspectFill" :src="item"></image>
              <!-- <uni-notice-bar v-if="isLink || detailInfo.remainStock!==0" class="notice-bar fs-12 font-normal" scrollable :speed="50"
								background-color="rgba(0, 0, 0, 0.30)" color="#FFF"
								:text="detailInfo.activeState===4 ? '活动已结束' : `活动将于${formatEndTime(detailInfo.endTime)}后结束`" /> -->
            </view>
            <view v-if="detailInfo.activeState === 4 || (!isLink && detailInfo.remainStock === 0)" class="swiper-stamp">
              <image v-if="detailInfo.activeState === 4" class="swiper-stamp-img" src="@/static/svg/activity/stamp-finished.svg"></image>
              <image v-else-if="detailInfo.remainStock === 0" class="swiper-stamp-img" src="@/static/svg/activity/stamp-snapped-up.svg"></image>
              <!-- <image class="swiper-stamp-img" src="@/static/svg/activity/stamp-sold-out.svg"></image> -->
            </view>
          </swiper-item>
        </swiper>
      </uni-swiper-dot>
      <danmu v-if="detailInfo.activeState === 3" :urlParams="paramsUrl" class="danmu" text="下单了+1"></danmu>
      <view class="flex justify-between top px-16 pt-12 pb-12 radius-8 radius-bl-0-i radius-br-0-i relative z-1" style="background: linear-gradient(to bottom, #FA4543, #FD6E4B); margin-top: -8px;">
        <view>
          <text class="fs-21 font-semibold leading-22 mb-4 mr-8 block">
            <text class="fs-14 font-normal">¥</text>
            {{ numberFormat(detailInfo.activeGroupBuy.groupBuyPrice) }}
          </text>
          <view class="flex">
            <text class="fs-14 font-normal leading-22 text-throughline mr-8">
              ¥{{ numberFormat(detailInfo.activePrice) }}
            </text>
            <tag v-if="detailInfo.userPointsAmt" class="block" custom-class="radius-12 color-primary-i px-12">
              下单得{{ detailInfo.userPointsAmt }}积分
            </tag>
          </view>
        </view>
        <view class="">
          <view class="flex justify-end mb-4">
            <tag class="block" custom-class="radius-12 color-primary-i px-12">拼团</tag>
          </view>
          <view class="fs-12 font-normal leading-22 flex item-center">
            已抢
            <image class="w-12 h-12" src="https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/pintuan-thunder.png">
            </image>
            {{ detailInfo.buyNum+ (detailInfo.virtualSaleNum?detailInfo.virtualSaleNum:0) }}份
          </view>
        </view>
      </view>

      <view class="flex-col radius-8 relative z-1" style="margin-top: -8px;">
        <view class="uni-bg-white radius-8 px-16 pt-16">
          <view>
            <tag class="mr-4">{{ detailInfo.promotionLabel }}</tag>
            <text class="text-color-regular fs-16 font-semibold leading-22 align-middle">
              {{ detailInfo.activeTitle }}
            </text>
          </view>
          <view class="mt-8 mb-12">
            <newcomer-coupon-tag v-if="detailInfo.activeRedPacket" class="mr-8" :price="numberFormat(detailInfo.activeRedPacket.firstRedPacketAmt)" @click="showRedPacket" />
            <template v-if="detailInfo.activeDiscount && detailInfo.activeDiscount.length">
              <full-discount-tag v-for="(item, index) in detailInfo.activeDiscount" :key="index" :data="item" class="mr-8" />
            </template>
          </view>
          <view v-if="isSignUp && detailInfo.activeStepPrices && detailInfo.activeStepPrices.length" class="mb-12">
            <sign-up-number-tag v-for="(item, index) in detailInfo.activeStepPrices" :key="index" :number="item.enrollNum" :price="item.enrollPrice" class="mr-8" />
          </view>
          <view class="flex justify-between item-center mt-8">
            <location-info :info="detailInfo.address"></location-info>
            <!-- 活动状态: 1-未发布，2-未开始 隐藏收藏按钮 -->
            <collect-button v-if="![1, 2].includes(detailInfo.activeState)" :userId="userStore.userInfo && userStore.userInfo.id" :activeId="detailInfo.id" :collectState="detailInfo.collectState" @onStateChange="toRefresh" />
          </view>
          <view class="flex flex-wrap mt-8">
            <view class="bg-primary cf fs-12 radius-4 mx-4 px-6 py-2">过期退</view>
            <view v-if="detailInfo.autoRefundEnabled" class="bg-primary cf fs-12 radius-4 mx-4 px-6 py-2">随时退</view>
          </view>
        </view>

        <view class="m-16">
          <view class="bg-default radius-12 px-12 py-16 flex justify-between flex-wrap item-center mt-8">
            <view class="text-center">
              <image src="https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/pintuan-flow1.png" style="width: 28px;height: 28px;"></image>
              <view class="fs-12 text-bold">开团/参团</view>
              <view class="fs-10" style="color:#969698">拼团享低价</view>
            </view>
            <view>
              <image src="https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/pintuan-next.png" style="width: 16px;height: 16px;"></image>
            </view>
            <view class="text-center">
              <image src="https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/pintuan-flow2.png" style="width: 28px;height: 28px;"></image>
              <view class="fs-12 text-bold">邀请好友参团</view>
              <view class="fs-10" style="color:#969698">分享优惠多</view>
            </view>
            <view>
              <image src="https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/pintuan-next.png" style="width: 16px;height: 16px;"></image>
            </view>
            <view class="text-center">
              <image src="https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/pintuan-flow3.png" style="width: 28px;height: 28px;"></image>
              <view class="fs-12 text-bold">人满拼团成功</view>
              <view class="fs-10" style="color:#969698">人不满退款</view>
            </view>
          </view>

          <view v-if="detailInfo.activeGroupBuy?.directJoinEnabled && pendingOrders.length" class="bg-default radius-12 px-12 py-16 flex justify-between flex-wrap item-center mt-8">
            <view class="fs-14 w-full text-bold mb-8">可直接参团</view>
            <view v-for="(item, index) in pendingOrders" :key="'pending_' + index" class="w-full flex justify-between mb-12 pl-12">
              <view class="flex">
                <view class="mr-8 flex item-center">
                  <image v-for="(avatarItem, ind) in item.members.slice(0, 2)" :key="avatarItem.userId" :src="avatarItem.avatar" class="w-28 h-28 round" :style="{ 'margin-left': ind ? '-15px' : 0, 'border': '0.5px solid #fff' }">
                  </image>
                  <image class="w-28 h-28 round" src="@/pagesA/static/svg/invite-user.svg" :style="{ 'margin-left': item.members.length ? '-15px' : 0, 'border': '0.5px solid #fff' }">
                  </image>
                </view>
                <view class="fs-12">
                  <view class="fs-12 flex leading-22 c3">
                    还差<view class="color-primary">{{ item.groupNum - item.currentNum }}人</view>成团
                  </view>
                  <view class="fs-10" style="color:#818181">剩余{{ formatEndTime(item.expiredTime) }}
                  </view>
                </view>
              </view>
              <view class="">
                <button class="radius-16 cf fs-12 px-8 py-2 leading-20" style="background: linear-gradient(to right, #FFDB8A, #FA4543);" @click="onActionClick('groupBuy', { groupBuyOrderId: item.groupBuyOrderId })">去参团</button>
              </view>
            </view>
          </view>

          <view v-if="detailInfo.agentState === 2 && detailInfo.haveAgent && (detailInfo.otherEquity || detailInfo.commissionAmt)" class="bg-default radius-12 px-12 py-16 mt-8">
            <view class="fs-14 w-full text-bold mb-8">经纪人推广权益</view>
            <view v-if="detailInfo.commissionAmt" class="flex fs-12 mb-8">
              <image class="w-16 h-16 mr-4" src="https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/pintuan-pig.png">
              </image>
              <view class="flex">佣金：<view class="color-primary">￥{{ detailInfo.commissionAmt }}</view>
              </view>
            </view>
            <view v-if="detailInfo.otherEquity" class="flex fs-12">
              <image class="w-16 h-16 mr-4" src="https://huodtg.oss-cn-hangzhou.aliyuncs.com/hd/miniprogram/pintuan-rank.png">
              </image>
              <view>可选权益：</view>
              <view class="">
                <text> {{ detailInfo.otherEquity?.replace(/\\n/g, '\n') }} </text>
              </view>
            </view>
          </view>

          <view class="bg-default radius-12 px-12 py-16 flex justify-between item-center flex-wrap mt-8">
            <view class="flex item-center flex-1">
              <image class="cu-avatar round size-44 mr-8 flex-shrink" :src="detailInfo.logo" @click="toMerchant">
              </image>
              <text class="fs-14 text-color-regular font-normal" @click="toMerchant">
                {{ detailInfo.businessShortName }}
              </text>
            </view>
            <subscribe-button class="flex-shrink" :userId="userStore.userInfo && userStore.userInfo.id" :businessId="detailInfo.businessId" :state="detailInfo.subscribeState" @onStateChange="toRefresh" />
            <view v-if="showIntegral" class="flex justify-center item-center w-full mt-8">
              <view class=" " @click="toIntegral">
                <image src="@/static/svg/mine/menu-integral.svg" class="w-16 h-16 mr-4 align-middle"></image>
                <text class="c3-6">前往积分商城 ></text>
              </view>
            </view>
          </view>

          <view v-if="detailInfo.activeGoods && detailInfo.activeGoods.length" class="mb-16">
            <view class="tabs">
              <view class="tab-item" :class="activeTab === 0 ? 'active' : ''" @click="activeTab = 0">
                <image v-if="activeTab === 0" mode="widthFix" class="absolute h-full" style="top:-8px;left:0;" src="@/static/svg/activity/bg-tab-start.svg"></image>
                <text style="z-index:1;">活动详情</text>
              </view>
              <view class="tab-item" :class="activeTab === 1 ? 'active' : ''" @click="activeTab = 1">
                <image v-if="activeTab === 1" mode="widthFix" class="absolute h-full" style="top:-8px;right:0;" src="@/static/svg/activity/bg-tab-end.svg"></image>
                <text style="z-index:1;">活动商品</text>
              </view>
            </view>
            <view class="tab-content">
              <activity-detail v-if="activeTab === 0" :showTitle="false" :content="detailInfo.content" />
              <view v-if="activeTab === 1" v-for="(goods, index) in detailInfo.activeGoods" :key="index" class="goods-item">
                <view class="flex justify-between">
                  <view class="image-warpper">
                    <view class="tip">x{{ goods.goodsNum }}</view>
                    <image class="w-48 h-48 radius-8" :src="goods.goodsImgs"></image>
                  </view>
                  <view class="flex-col">
                    <text class="text-color-regular text-bold fs-14 mb-8">{{ goods.goodsName
											}}</text>
                    <view class="flex" @click="showInstructionDialog(goods.id)">
                      <text class="fs-12 text-color-hint">可用商户&使用说明</text>
                      <image class="w-16 h-16" src="@/static/svg/activity/icon-more.svg"></image>
                    </view>
                  </view>
                </view>
                <!-- 多商户不显示 -->
                <image v-if="goods.mulState === 1" class="w-28 h-28" src="@/static/svg/activity/icon-goods-service.svg" @click="showServiceDialog(goods)">
                </image>
              </view>
            </view>
          </view>
          <view v-else class="mt-8 mb-16">
            <activity-detail :content="detailInfo.content" />
          </view>
        </view>
      </view>
      <Recommend v-if="detailInfo" :activeId="detailInfo.id" :businessId="detailInfo.businessId" />
    </scroll-view>
    <view v-if="isLink || detailInfo.remainStock !== 0" class="footer bg-white" :style="`padding-bottom:${safeAreaBottom}px;`">
      <activity-footer :data="detailInfo" type="groupBuy" @onActionClick="onActionClick"></activity-footer>
    </view>
    <template>
      <RedPacketDialog v-if="detailInfo.activeRedPacket" ref="redPacketDialog" :data="detailInfo.activeRedPacket" @receiveSuccess="toRefresh" />
      <service-dialog :phoneNumber="detailInfo.activeMobile" :weixin="detailInfo.activeWechat" ref="serviceDialog" />
      <instructions-dialog ref="instructionDialog" />
      <OrderPopup ref="orderPopup" :data="detailInfo" :code="code" />
      <GroupBuyOrderPopup ref="groupBuyOrderPopup" :data="detailInfo" :code="code" :group-buy-order-id="groupBuyOrderId" :is-zero-group-buy="!!detailInfo.leadFreeEnabled" :ext-params="groupBuyOrderExtParams" />
      <PromotionIncentiveDialog ref="promotionIncentiveDialog" :commissionAmt="preShareData && preShareData.commissionAmt" :otherEquity="preShareData && preShareData.otherEquity" :pointsAmt="preShareData && preShareData.pointsAmt" @onConfirm="handlePromotionInterset" @onCancel="onClosePromotionInterset" />
    </template>
    <share-activity :id="detailInfo.id" :show="showSharePopup" @onClose="showSharePopup = false" :options="{groupBuyLabel:detailInfo.promotionLabel}" />
    <!-- 裁剪分享时图片的canvas -->
    <canvas style="position: absolute; top: -1000px; left: -1000px; width: 640px; height: 640px; background: #000;" canvas-id="canvas"></canvas>
  </view>
</template>

<script setup name="ActivityDetail">
import {
  onLoad,
  onShareAppMessage,
  onShow,
} from '@dcloudio/uni-app'
import {
  ref,
  computed,
  watch
} from 'vue'
import { useUserStore } from '@/stores/modules/user.js'
import FullDiscountTag from '@/components/full-discount-tag/full-discount-tag.vue'
import RedPacketDialog from './components/red-packet-dialog.vue'
import ServiceDialog from '@/components/service-dialog/service-dialog.vue'
import OrderPopup from './components/order-popup.vue'
import GroupBuyOrderPopup from './components/group-buy-order-popup.vue'
import ActivityDetail from './components/activity-detail/activity-detail.vue'
import ActivityFooter from './components/activity-footer/activity-footer.vue'
import PromotionInterest from './components/promotion-interest/promotion-interest.vue'
import Danmu from './components/danmu/danmu.vue'
import { activeDetailsApi, } from '@/api/activity.js'
import { getActiveOrderNumApi, getPendingGroupBuyOrdersApi } from '@/api/order.js'
import {
  numberFormat,
  parseScene,
  isVideoFile
} from '@/utils/index.js'
import { useActivity } from '@/hooks/useActivity.js'
import Recommend from '@/pagesF/components/recommend/recommend.vue'
import Tag from '@/components/tag/tag.vue'
import PromotionIncentiveDialog from '@/components/share-activity/promotion-incentive-dialog.vue'
import { useShare } from '@/hooks/useShare.js'
import {
  formatEndTime,
} from '@/utils/index.js'


const userStore = useUserStore()
const { isSignUp, isLink, photos, coverPicture, updateActivityInfo } = useActivity(detailInfo)

const navBar = ref(null)
const navBarHeight = computed(() => {
  const statusBarHeight = uni.getWindowInfo().statusBarHeight
  const navigationBarHeight = statusBarHeight + (navBar.value && navBar.value.height || 0)
  return navigationBarHeight
})
const safeAreaBottom = computed(() => {
  return uni.getSystemInfoSync().safeAreaInsets.bottom
})

const goBack = () => {
  // 仅有一个页面时，返回首页
  if (getCurrentPages().length === 1) {
    uni.reLaunch({
      url: '/pages/home/home'
    })
    return
  }
  uni.navigateBack()
}

const swiperDotIndex = ref(0)
const swiperChange = (e) => {
  swiperDotIndex.value = e.detail.current
}

const toMerchant = () => {
  uni.navigateTo({
    url: `/pagesA/merchant/homepage?id=${detailInfo.value.businessId}`
  })
}

const showIntegral = computed(() => {
  return userStore.userInfo?.businessInfo?.pointsMallState === 1
});
const toIntegral = () => {
  const url = userStore.userInfo?.businessInfo?.id === detailInfo.value.businessId
    ? `/pagesJ/integralSetting/mall`
    : `/pagesF/merchantMall/index?id=${detailInfo.value.businessId}`
  uni.navigateTo({
    url
  })
}

// 活动详情、活动商品Tab
const activeTab = ref(0)
const scrollTop = ref(0)

watch(activeTab, () => {
  console.log('切换tab', activeTab, scrollTop.value)
  scrollTop.value = 0
})

// 领取红包状态：1-未领取，2-未使用，3-已使用
const redPacketDialog = ref(null)
const showRedPacket = () => {
  if (detailInfo.value.activeState === 4) return // 已结束，不需要响应
  if (userStore.isLogin) {
    // if (detailInfo.value.activeRedPacket.receiveState !== 3) {
    redPacketDialog.value.showDialog(true)
    // }
  } else {
    const url = detailInfo.value.promotionType === 'GROUP_BUY'
      ? `/pagesB/activity/activity-group-buy`
      : `/pagesB/activity/activity`;
    uni.navigateTo({
      url: `/pagesA/login/login?from=${encodeURIComponent(`${url}?id=${id.value}&_from=BActivityGroupBuy`)}`,
      events: {
        onLoginSuccess() {
          toRefresh()
        }
      }
    })
  }
}

const serviceDialog = ref(null)
const showServiceDialog = (goods) => {
  console.log('客服', goods, serviceDialog.value)
  serviceDialog.value.showDialog(true, goods)
}

const instructionDialog = ref(null)
const showInstructionDialog = (activeGoodsId) => {
  instructionDialog.value.showDialog(true, activeGoodsId, 'activeGoodsId')
}

const orderPopup = ref(null)
const showOrderPopup = () => {
  orderPopup.value.show(true)
}

const { preShareData, getPreShare } = useShare()

const groupBuyOrderPopup = ref(null)
const groupBuyOrderExtParams = ref({});
const showGroupBuyOrderPopup = () => {
  groupBuyOrderExtParams.value = {};
  if (detailInfo.value.agentState === 2 && detailInfo.value.haveAgent) {
    getPreShare(detailInfo.value.id).then(res => {
      if (res.popupState) {
        promotionIncentiveDialog.value && promotionIncentiveDialog.value.showDialog(true);
      } else {
        const rewardType = res.commissionAmt ? 1 : res.otherEquity ? 2 : res.pointsAmt ? 3 : 0;
        handlePromotionInterset(rewardType)
      }
    })
  } else {
    groupBuyOrderPopup.value.show(true)
  }
}

const showSharePopup = ref(false)

const onActionClick = (type, params) => {
  console.log('onActionClick', type)
  if (type === 'service') {
    showServiceDialog()
  } else if (type === 'home') {
    uni.navigateTo({
      url: '/pages/home/home'
    })
  } else if (type === 'share') {
    if (userStore.isLogin) {
      showSharePopup.value = true
    } else {
      const url = detailInfo.value.promotionType === 'GROUP_BUY'
        ? `/pagesB/activity/activity-group-buy`
        : `/pagesB/activity/activity`;
      uni.navigateTo({
        url: `/pagesA/login/login?from=${encodeURIComponent(`${url}?id=${id.value}&_from=BActivityGroupBuy`)}`,
        events: {
          onLoginSuccess() {
            toRefresh()
          }
        }
      })
    }
  } else if (type === 'buy') {
    if (userStore.isLogin) {
      if (isLink.value) {
        uni.navigateTo({
          url: `/pagesC/webview/webview?url=${encodeURIComponent(detailInfo.value.activeUrl)}`
        })
      } else {
        showOrderPopup()
      }
    } else {
      const url = detailInfo.value.promotionType === 'GROUP_BUY'
        ? `/pagesB/activity/activity-group-buy`
        : `/pagesB/activity/activity`;
      uni.navigateTo({
        url: `/pagesA/login/login?from=${encodeURIComponent(`${url}?id=${id.value}&_from=BActivityGroupBuy`)}`,
        events: {
          onLoginSuccess() {
            toRefresh()
          }
        }
      })
    }
  } else if (type === 'groupBuy') {
    if (userStore.isLogin) {
      if (isLink.value) {
        uni.navigateTo({
          url: `/pagesC/webview/webview?url=${encodeURIComponent(detailInfo.value.activeUrl)}`
        })
      } else {
        groupBuyOrderId.value = params?.groupBuyOrderId;
        showGroupBuyOrderPopup()
      }
    } else {
      const url = detailInfo.value.promotionType === 'GROUP_BUY'
        ? `/pagesB/activity/activity-group-buy`
        : `/pagesB/activity/activity`;
      uni.navigateTo({
        url: `/pagesA/login/login?from=${encodeURIComponent(`${url}?id=${id.value}&_from=BActivityGroupBuy`)}`,
        events: {
          onLoginSuccess() {
            toRefresh()
          }
        }
      })
    }
  } else if (type === 'signup') {
    if (userStore.isLogin) {
      // 报名次数用完，点击立即报名，toast“您的报名次数已用完‘，不弹出支付面板
      if (detailInfo.value.limitEnrollNum) {
        getActiveOrderNumApi({
          activeId: id.value
        }).then(res => {
          return detailInfo.value.limitEnrollNum - res > 0
        }).then(res => {
          if (res == true) {
            showOrderPopup()
          } else {
            uni.showToast({
              icon: 'none',
              title: '您的报名次数已用完'
            })
          }
        })
      } else {
        showOrderPopup()
      }
    } else {
      const url = detailInfo.value.promotionType === 'GROUP_BUY'
        ? `/pagesB/activity/activity-group-buy`
        : `/pagesB/activity/activity`;
      uni.navigateTo({
        url: `/pagesA/login/login?from=${encodeURIComponent(`${url}?id=${id.value}&_from=BActivityGroupBuy`)}`,
        events: {
          onLoginSuccess() {
            toRefresh()
          }
        }
      })
    }
  }
}

const groupBuyOrderId = ref();
const id = ref('')
const detailInfo = ref(undefined)
const code = ref('') // 活动分享码
const shareImg = ref('')

const paramsUrl = ref('')
const getDetail = () => {
  activeDetailsApi(id.value, code.value || '').then(res => {
    detailInfo.value = res
    updateActivityInfo(res)
    cutShareImg(getFirstImage(res.activeImg))
    getPendingOrders();
  }).catch(err => {
    uni.showToast({
      icon: 'none',
      title: err.message
    })
    if (err.code == 10014) {//链接失效
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/home/home'
        })
      }, 1000)

    }
  })
}

const pendingOrders = ref([]);
const getPendingOrders = () => {
  if (!detailInfo.value.activeGroupBuy?.directJoinEnabled) return;
  getPendingGroupBuyOrdersApi({ id: detailInfo.value.id }).then(res => {
    pendingOrders.value = res.slice(0, 2);
    if (pendingOrders.value.length) {
      pendingOrders.value.forEach((item) => {
        item.members.sort((a, b) => {
          return -(a.groupLead - b.groupLead)
        });
        item.members = item.members.slice(0, 2);
      })
    }
  })
};

const toRefresh = () => {
  getDetail()
}

onShow(() => {
  getDetail()
})
onLoad(query => {
  uni.hideShareMenu()
  console.log('活动详情', query, query.scene)
  id.value = query.id
  code.value = query.code
  groupBuyOrderId.value = query.groupBuyOrderId;
  // 扫码打开
  if (query.scene) {
    const scene = parseScene(query.scene)
    if (!query.id && scene.aId) {
      id.value = scene.aId
      code.value = scene.code
    }
  }

  const url = !detailInfo.value || detailInfo.value.promotionType === 'GROUP_BUY'
    ? `/pagesB/activity/activity-group-buy`
    : `/pagesB/activity/activity`;
  paramsUrl.value = `from=${encodeURIComponent(`${url}?id=${id.value}&_from=BActivityGroupBuy`)}`
  getDetail()
})

onShareAppMessage((options) => {
  console.log('活动分享', options)
  const url = detailInfo.value.promotionType === 'GROUP_BUY'
    ? `/pagesB/activity/activity-group-buy`
    : `/pagesB/activity/activity`;
  return {
    title: options.target.dataset.title,
    path: `${url}?id=${options.target.dataset.activityId}&code=${options.target.dataset.shareCode}&_from=BActivityGroupBuy`,
    imageUrl: shareImg.value
  }
})

const getFirstImage = (activeImg) => {
  const arr = activeImg && activeImg.split(',') || []
  const imgPath = arr.find(path => !isVideoFile(path))
  return imgPath
}

//裁剪分享的图片为5:4
//传入图片地址
const cutShareImg = (imgurl) => {
  uni.getImageInfo({
    src: imgurl,  // 这里填写网络图片路径
    success: (res) => {
      let ctx = uni.createCanvasContext('canvas');
      let canvasW = 640,
        canvasH = 500; // 5:4 的比例

      let imgAspect = res.width / res.height;
      let canvasAspect = canvasW / canvasH;

      if (imgAspect > canvasAspect) { // 图片宽度较大，需要按照高度裁剪
        let destHeight = res.height;
        let destWidth = destHeight * canvasAspect;

        let offsetX = (res.width - destWidth) / 2;
        let offsetY = 0; // 图片高度不变，从顶部开始裁剪

        ctx.drawImage(res.path, offsetX, offsetY, destWidth, destHeight, 0, 0, canvasW, canvasH);
      } else { // 图片高度较大，按照宽度裁剪
        let destWidth = res.width;
        let destHeight = destWidth / canvasAspect;

        let offsetX = 0; // 图片宽度不变，从左侧开始裁剪
        let offsetY = (res.height - destHeight) / 2;

        ctx.drawImage(res.path, offsetX, offsetY, destWidth, destHeight, 0, 0, canvasW, canvasH);
      }
      ctx.draw(false, () => {
        uni.canvasToTempFilePath({
          width: canvasW,
          height: canvasH,
          destWidth: canvasW,
          destHeight: canvasH,
          canvasId: 'canvas',
          fileType: 'jpg',
          success: (res) => {
            //设置分享图片路径
            shareImg.value = res.tempFilePath
          }
        })
      })
    }
  });
}

const promotionIncentiveDialog = ref(null);
const handlePromotionInterset = (val) => {
  groupBuyOrderExtParams.value.rewardType = val;
  groupBuyOrderPopup.value.show(true)
};

const onClosePromotionInterset = () => {

}

</script>

<style lang="scss" scoped>
:root {
  .uni-noticebar {
    margin-bottom: 0;
  }
}

.danmu {
  position: absolute;
  left: 16px;
  top: 114px;
}

.swiper-box {
  height: 250px;
  background-color: #000;
}

.swiper-item {
  height: 250px;
  position: relative;

  .notice-bar {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 36px;
  }
}

.swiper-stamp {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
}

.swiper-stamp-img {
  width: 160px;
  height: 160px;
}

.top {
  color: #fff;
}

.stoce {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  height: 20px;
  min-width: 64px;
  padding: 4px 0px;
  border-image-source: url('@/static/svg/activity/bg-stock.svg');
  border-image-slice: 0 8 0 8 fill;
  border-right: 8px solid;
  border-left: 8px solid;
  color: #fff;
  font-size: 10px;
  font-style: normal;
  font-weight: 400;
  line-height: normal;
}

.tabs {
  margin-top: 16px;
  display: flex;
  background-color: #f5f5f5;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;

  .tab-item {
    position: relative;
    height: 52px;
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    color: rgba(51, 51, 51, 0.6);
    font-size: 16px;
    font-weight: 500;
    line-height: 22px;

    &.active {
      color: #fa4543;
      font-size: 16px;
      font-style: normal;
      font-weight: 600;
      line-height: 22px;
    }
  }
}

.tab-content {
  background-color: #f5f5f5;
  padding: 18px 12px 10px;
  border-bottom-left-radius: 12px;
  border-bottom-right-radius: 12px;

  .image-warpper {
    position: relative;
    margin-right: 12px;

    .tip {
      font-size: 8px;
      z-index: 1;
      color: #333;
      background: #fbdbb0;
      position: absolute;
      right: 0;
      top: 0;
      border-radius: 0 8px 0 8px;
      padding: 2px 6px;
    }
  }
}

.goods-item {
  display: flex;
  padding: 8px 12px;
  justify-content: space-between;
  align-items: center;
  border-radius: 8px;
  background: #fff;

  .img {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    margin-right: 12px;
  }

  &:not(:last-child) {
    margin-bottom: 8px;
  }
}

.footer {
  min-height: 52px;
}
</style>
